import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

# 1. 读取数据
file_path = "省份数据.csv"
try:
    data = pd.read_csv(file_path, encoding="gbk")
except UnicodeDecodeError:
    data = pd.read_csv(file_path, encoding="latin1")

# 2. 数据清洗
# 删除不需要的列（如果存在），保留数值列
data_cleaned = data.drop(columns=["颗粒物排放量(万吨)", "每十万人高校在校生数", "医疗卫生机构床位数(万张)", "地区"], errors="ignore")

# 3. 确保只选择数值列（防止有非数值列混入）
data_numeric = data_cleaned.select_dtypes(include=['number'])

# 4. 数据标准化
scaler = StandardScaler()
data_standardized = scaler.fit_transform(data_numeric)

# 5. PCA降维到2维，便于可视化
pca = PCA(n_components=2)
data_pca = pca.fit_transform(data_standardized)

# 6. K-Means聚类分析
n_clusters = 3  # 设置聚类的簇数
kmeans = KMeans(n_clusters=n_clusters, n_init=10, random_state=42)
clusters = kmeans.fit_predict(data_standardized)

# 7. 将聚类结果加入原始数据
data['聚类类别'] = clusters

# 8. 计算每个类别的平均值
cluster_means = data.groupby('聚类类别')[['地区生产总值(亿元)', '一般预算收入(亿元)', '商品房平均销售价格(元/平方米)']].mean()
print("每个类别的平均值：")
print(cluster_means)

# 9. 可视化：散点图展示聚类结果
plt.figure(figsize=(8, 6))
for cluster in range(n_clusters):
    plt.scatter(data_pca[clusters == cluster, 0],
                data_pca[clusters == cluster, 1],
                label=f"类别 {cluster}")

plt.scatter(kmeans.cluster_centers_[:, 0],
            kmeans.cluster_centers_[:, 1],
            c='red', marker='x', s=200, label='聚类中心')

plt.title("K-Means 聚类结果散点图")
plt.xlabel("PCA 主成分 1")
plt.ylabel("PCA 主成分 2")
plt.legend()
plt.show()
